<?php
defined('BASEPATH') OR exit('No direct script access allowed');

//支付
class Pay extends MY_Controller {

	function __construct(){
		parent::__construct();
		
		$this->load->library('Weixin');
		$this->debug = true;
	}	
	
	function VerifToken(){
		return true;
	}
	
	
	function notify_url(){
		
		$data = file_get_contents("php://input");
		if($this->debug){
			file_put_contents('test_pay.txt',$data);
		}
		
		
		$result_data = $this->weixin->xmlToArray($data);
		
		if($result_data['return_code']!='SUCCESS'){
			$this->err_out($result_data['return_msg']);
		}
		
		if($result_data['result_code']!='SUCCESS'){
			$this->err_out('接口提交成功，但是业务结果错误');
		}
		
		$this->load->model('Index/PayLogModel', 'paylog');
		$this->load->model('Index/CourseCardModel', 'card');
		$this->load->model('User/UserCardModel', 'ucard');
		$this->load->model('User/UserCardLogModel', 'card_log');
		
		$order_sn = $result_data['out_trade_no'];
		$info = $this->paylog->order_get_info($order_sn);
		if(!$info){
			$this->err_out('订单错误');
		}
		
		if($info['amount']*100!=$result_data['total_fee']){
			$this->err_out('参数错误');
		}
		
		$user_id = $info['user_id'];
		$id = $info['card_id'];
		
		$time = time();		

		
		$card_info = $this->card->get_info($id);
		if(!$card_info){
			$this->err_out('数据不存在');
		}
		
		
		$user_card = array(
			"user_id"  => $user_id,
			"cid"	   => $card_info['course_id'],
			"card_id"  => $id,
			"total_num"=> $card_info['course_num'],
			"num"	   => $card_info['course_num'],
			"price"    => $card_info['price'],			
			"addtime"  => $time
		);		
		$res = $this->ucard->add($user_card);

		$card_log = array(
			"user_id"  => $user_id,				
			"card_id"  => $id,				
			"price"    => $card_info['price'],
			"num"      => $card_info['course_num'],
			"info"	   => '购卡成功！',
			"addtime"  => $time
		);
		$res_log = $this->card_log->add($card_log);
		$parr = array(
			'status'=>1,
			'transaction_id'=>$result_data['transaction_id'],
			'pay_time'=>$time
		);
		
		$this->paylog->edit($parr,"id='{$info['id']}'");
		
		if(!empty($info['form_id'])){
			$this->load->model('User/UserModel', 'user');
			$user = $this->user->get_info($user_id);
			if(!$user){
				$this->err_out('用户不存在');
			}
			
			$this->send_msg($user['openid'],$info);
			
		}
		
		
		$arr = array(
			'return_code'=>'<![CDATA[SUCCESS]]>',
			'return_msg'=>'<![CDATA[OK]]>',
		);
		$xml = $this->weixin->data_to_xml($arr);
		die($xml);
	}
	
	function send_msg($openid,$order){

		
		$this->load->library('Weixin');
		$tokens = $this->get_access_token();
		if(!$tokens){
			$this->err_out('获取token错误');
		}
		$url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token={$tokens['access_token']}";
		
		$arr = array();
		
		
		$arr['touser'] = $openid;
		$arr['weapp_template_msg'] = array(
			'template_id'=>'ZqvudmxnuVgygze1C_rR_EgRhRTP1honkaZOKXK9_uA',
			'page'=>"pages/home/home",
			'form_id'=>$order['form_id'],
			'data'=>array(
				'keyword1'=>array('value'=>$order['order_sn']), //单号
				'keyword2'=>array('value'=>$order['amount']), //金额
				'keyword3'=>array('value'=>date('Y-m-d H:i:s',$order['addtime'])), //下单时间
				'keyword4'=>array('value'=>$order['goods_name']), //物品名称
				'keyword5'=>array('value'=>date('Y-m-d H:i:s')), //支付时间
				'keyword6'=>array('value'=>'微信支付'), //支付方式
			),
			'emphasis_keyword'=>''
		);
		
		$ww = $this->weixin->post_curls($url,json_encode($arr));
		$data = json_decode($ww,true);
		if(!$data){
			$this->err_out('发送消息失败');
		}
		
		$this->out($data);
	}
	
	function get_access_token(){
		$token_file = FCPATH . 'access_token.txt';
		$time = time();
		
		$ww = file_get_contents($token_file);
		if($ww){
			$data = json_decode($ww,true);
			if($data && $time<$data['endtime']){
				return $data;
			}
		}
		
		$this->load->model('Admin/ConfigModel', 'cfg');
		
		$appid = $this->cfg->get_config('UserAppID');
		if(!$appid){
			$this->err_out('请先配置AppID');
		}
		$AppSecret = $this->cfg->get_config('UserAppSecret');
		if(!$AppSecret){
			$this->err_out('请先配置AppSecret');
		}
		
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$AppSecret}";
		$ww = $this->weixin->get_url($url);
		
		$data = json_decode($ww,true);
		if(!$data){
			return false;
		}
		
		$endtime = $time + $data['expires_in'];
		$arr = array(
			'access_token'=>$data['access_token'],
			'endtime'=>$endtime
		);
		file_put_contents($token_file,json_encode($arr));
		return $arr;
	}

}
